import { StoreActionType } from '@/Editor/store/module';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { EditorContext } from '../../index';
import AxisRuler, { AxisRulerRect } from '../AxisRuler';
import DragToSelectContainer from '../DragToSelect';

import ModuleOption from '../ModuleOption';

import RndModule from '../RndModule';
import StyleModule from './../../style.module.less';
import { DefaultInnerRect, DefaultOuterRect } from './config';

const ModuleCanvas: React.FC = () => {
  const {
    dispatch,
    storeState: { selectModuleDataIds, moduleDataList },
  } = useContext(EditorContext);
  // 防止调用findNode
  const editorModuleCanvasRef = React.createRef<HTMLDivElement>();
  const outerRectRef = useRef<HTMLDivElement>(null);
  const innerRectRef = useRef<HTMLDivElement>(null);
  const [outerRect, setOuterRect] = useState<AxisRulerRect>({
    ...DefaultOuterRect,
  });
  const [innerRect, setInnerRect] = useState<AxisRulerRect>({
    ...DefaultInnerRect,
  });

  useEffect(() => {
    const outerRectElement = outerRectRef.current;
    const innerRectElement = innerRectRef.current;
    if (outerRectElement && innerRectElement) {
      setOuterRect(outerRectElement.getBoundingClientRect());
      setInnerRect(innerRectElement.getBoundingClientRect());
    }
  }, []);

  return (
    <DragToSelectContainer nodeRef={editorModuleCanvasRef}>
      <div id={StyleModule['editor-module-canvas']} ref={editorModuleCanvasRef}>
        {/* 绘制标尺 start */}
        <div className="axis-ruler-container">
          <AxisRuler outerRect={outerRect} innerRect={innerRect} />
        </div>
        {/* 绘制标尺 end */}
        <div className="editor-module-canvas-inner" ref={outerRectRef}>
          <div
            className="module-canvas"
            ref={innerRectRef}
            tabIndex={0}
            style={{ outline: 'none' }}
            onKeyDown={(event) => {
              const { key } = event;
              // 删除 所有选中元素
              if (key === 'Backspace' || key === 'Delete') {
                dispatch?.({
                  type: StoreActionType.DeleteModuleDataList,
                  payload: {
                    moduleDataIds: selectModuleDataIds,
                  },
                });
              }
            }}
          >
            {/* 绘制所有的组件 start */}
            {moduleDataList.map((moduleData) => {
              return <RndModule moduleData={moduleData} key={moduleData.id} />;
            })}
            {/* 绘制所有的组件 end */}

            {/* 绘制操作选项 start */}
            <ModuleOption />
            {/* 绘制操作选项 end */}
          </div>
        </div>
      </div>
    </DragToSelectContainer>
  );
};

export default ModuleCanvas;
